package com.library.www.util;

import java.sql.*;

public class BaseDao {
    public String Driver="com.mysql.jdbc.Driver";
    public String url="jdbc:mysql://1.116.221.28:3306/book?useUnicode=true&characterEncoding=utf8";
    public String zhang="root";//用户名
    public String pwd="ybpaeee7aiNa.";//密码
    public Connection conn=null;
    /*
     * 连接方法
     * */
    public Connection getConn () {
        try {
            Class.forName(Driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        try {
            conn= DriverManager.getConnection(url,zhang,pwd);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return conn;
    }
    /**
     * 关闭连接
     */
    public void Closes(Connection conn, PreparedStatement ps, ResultSet rs){
        if (conn!=null){
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }if (ps!=null){
            try {
                ps.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }if (rs!=null){
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    /*
     * 增删改
     * */
    public int executeUpdate(String sql,Object... objects){
        Connection connection=getConn();
        int sum=0;
        try {
            PreparedStatement pst=connection.prepareStatement(sql);
            for(int i=0;i<objects.length;i++){
                pst.setObject(i+1,objects[i]);
            }
            sum=pst.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return sum;
    }
    /*
     * 查询
     * */
    public ResultSet executeQuery(String sql,Object... arr){
        conn=getConn();
        ResultSet rs=null;//接受返回值
        PreparedStatement pstms=null;//执行sql语句的对象
        try {
            pstms=conn.prepareStatement(sql);
            for (int i=0;i<arr.length;i++){
                pstms.setObject(i+1,arr[i]);
            }
            rs=pstms.executeQuery();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return rs;
    }
}
